package cn.hackcloud.config.config;

import cn.hackcloud.config.annotation.EnableGlobalConfig;
import cn.hackcloud.config.scope.RefreshScopeRegistry;
import cn.hackcloud.config.zookeeper.CuratorUtil;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

/**
 * @author Administrator
 */
public class ConfigRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        Map<String, Object> attributes = metadata.getAnnotationAttributes(EnableGlobalConfig.class.getName(), true);
        Object mode = attributes.get("mode");
        if ("zk".equals(mode.toString())) {
            registerZkConfig(registry);
        } else if ("redis".equals(mode.toString())) {
            registerZkConfig(registry);
        }
    }

    private void registerZkConfig(BeanDefinitionRegistry registry) {
        BeanDefinitionBuilder zookeeperClient = BeanDefinitionBuilder.genericBeanDefinition(CuratorUtil.class);
        BeanDefinitionBuilder refreshScope = BeanDefinitionBuilder.genericBeanDefinition(RefreshScopeRegistry.class);
        registry.registerBeanDefinition("cn.hackcloud.config.zookeeper.CuratorUtil", zookeeperClient.getBeanDefinition());
        registry.registerBeanDefinition("cn.hackcloud.config.scope.RefreshScopeRegistry", refreshScope.getBeanDefinition());
    }
}
